package com.sh.springbootinit.manager;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Auther: sh
 * @Version 1.0
 * @Description: 文件上传管理器
 */
@Component
public class OssManager {
    @Autowired
    private OSS ossClient;

    @Autowired
    private String bucketName;

    /**
     * 上传文件到 OSS
     * @param file       MultipartFile 文件对象
     * @param ossFileName OSS 上的文件名
     * @return 上传后的 OSS 文件路径
     */
    public String uploadFileToOSS(MultipartFile file, String ossFileName) {
        try {
            // 获取文件的输入流
            InputStream inputStream = file.getInputStream();
            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, ossFileName, inputStream, null);
            // 执行上传
            ossClient.putObject(putObjectRequest);
            System.out.println("文件上传成功：" + ossFileName);

            // 返回文件的 OSS 访问路径
            return "https://" + bucketName + "." + "oss-cn-wuhan-lr.aliyuncs.com" + "/" + ossFileName;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件上传失败：" + e.getMessage());
            return null;
        } finally {
            try {
                if (file.getInputStream() != null) {
                    file.getInputStream().close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

